#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<fcntl.h>

int flag = 0; 
#define FileName "log.txt"
#define NO_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3


void test(int argc, char* argv[])
{
    int i = 0;
    for(; argv[i] ; i++)
    {
        printf("%s\n", argv[i]);
    }
    return ;
}
void FindSymbol(int argc, char* argv[])
{
    flag =0;
    int i = 0;
    for(; i <argc; i++)
    {
        if(strcmp(argv[i] , "<") == 0)
        {
            flag = 1;
            argv[i] = NULL;
            break;
        }
        else if(strcmp(argv[i] , ">" ) == 0)
        {
            flag = 2;
            argv[i] = NULL;
            break;
        }
        else if(strcmp(argv[i] , ">>") == 0)
        {
            flag = 3;
            argv[i] =NULL;
            break;
        }
    }
    return ;
}

void Delete(int argc ,char * argv[])
{
    int prev = 0;
    int next = prev + 1;
    for(; next <=  argc; prev++,next++)
    {
        argv[prev] = argv[next];
    }
    return ;
}

int main(int argc, char* argv[])
{
    Delete(argc, argv);
    argc--;
    if(argc == 0)
    {
        printf("No CMD!\n");
        exit(1);
    }

    test(argc , argv);
    //printf("flag = %d!!!!!!\n",flag);
    fflush(stdout);
    sync();
    //创建子进程
    int pid = fork();
    if(pid == 0)
    {
        
         FindSymbol(argc , argv);//判断是否是重定向，每次判断前flag = 0
         printf("flag = %d\n???" ,flag);
        //子进程
        if(flag == INPUT_REDIR)
        {
            //输入重定向

            int fd = open(FileName , O_RDONLY);
            if(fd < 0 )
            {
                exit(2);
            }
            dup2(fd,0);
            close(fd);
        }
        else if(flag == OUTPUT_REDIR)
        {
            //输出重定向
            int fd = open(FileName, O_CREAT|O_WRONLY|O_TRUNC, 0666);
            if(fd < 0)
            {
                exit(3);
            }
            dup2(fd , 1);
            close(fd);
        }
        else if(flag == APPEND_REDIR)
        {
            //追加重定向
            int fd = open(FileName, O_CREAT|O_WRONLY, 0666);
            if(fd < 0)
            {
                exit(4);
            }
            dup2(fd , 1);
            close(fd);
        }
       // else
       // {
       //     //没有重定向
       //     exit(0);
       // }
        
        printf("flag = %d\n????????????",flag);
        //std::cout << argv[0] << argv[1] << argv[2] << std::endl;
        printf("%s", argv[0]);
        execvp(argv[0] , argv);
        exit(0);
    }


    //父进程
    int status; 
    int ret = waitpid(pid , &status , 0);
    if(ret < 0)
    {
        printf("Wait Wrong!,status : %d\n",status);

    }
    return 0;
}
